var _step        = 1;
var _guestOpener = '';
var _weekdays    = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');

$(function() {
    user.init();

    $('#dialog-message').dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        show: 'puff',
        hide: 'puff',
        buttons: {
            Ok: function() {
                $(this).dialog('close');
            }
        }
    });

    $('div.tabs').tabs({
        select: function(event, ui){
            ui.tab.blur();
            $.validationEngine.closePrompt('.formError');
        }
    });

    $('.formMessage').click(function(){
        if ($(this).hasClass('error') || $(this).hasClass('red')) {
            $(this).removeClass('error red').html('');
        }
    });

    $('select.roomType').linkselect({
        classContainer: 'linkselectContainer',
        format: function (code, value, label, pos){
            return '<div class="fLeft" style="width:50px;">'+code+'</div><div class="fLeft">'+_roomTypes[value]+'</div><div class="clear"></div>';
        },
        change: function(){
            if ($('#reservation-form-wrap').dialog('isOpen')) {
                setTimeout(function(){
                    share.roomRate('rsv-');
                }, 200);
            }
        },
        titleAlign: 'left'
    });

    $('input.spinbox').spinbox({
        min: 0,
        max: 999,
        step: 1
    }).attr('autocomplete', 'off');
    $('input.spinbox1').spinbox({
        min: 1,
        max: 999,
        step: 1
    }).attr('autocomplete', 'off');

    $('.onlyMoney').attr('autocomplete', 'off');
    $('.onlyMoney').keyup(function(event) {
        var k = false;

        if (typeof(event.keyCode) == 'number') {
            k = event.keyCode;
        } else if (typeof(event.which) == 'number') {
            k = event.which;
        } else if (typeof(event.charCode) == 'number') {
            k = event.charCode;
        }

        var keychar = String.fromCharCode(k);

        if (k == null || k == 0 || k == 8 || k == 9 || k == 13 || k == 27 || k == 37 || k == 39 || k == 116) { // control keys
            return true;
        } else if (('.0123456789').indexOf(keychar) > -1) {
            return true;
        } else {
            var str = '';

            jQuery.each($(this).val(), function(i, s){
                if (('.0123456789').indexOf(s) > -1) {
                    str += s;
                }
            });

            $(this).val(str);
            return false;
        }
    }).change(function(){
        $(this).val(number_format($(this).val(), 2));
    });

    $('button', '.button').button();
    $('button.disabled').button('disable');
    $('button.close').click(function(){
        $(this).parents('div.dialog').dialog('close');
    });
});


var user = {
    ext: 'lgn-',
    dialog1: 'user-info-wrap',
    dialog2: 'user-form-wrap',
    dialog3: 'login-wrap',
    form_name: 'UserSaveForm',
    form3: 'UserLoginForm',
    grid_name: 'userlist',
    username: '',
    opener: false,

    init: function() {
        var ext = this.ext;

        if ($('#'+ext+'id').val()) { // have already login
            return;
        }

        if (!$('.ui-dialog #'+this.dialog3).length) {
            $('#'+this.form3).validationEngine();

            $('#'+this.dialog3).dialog({
                width: 'auto',
                resizable: false,
                modal: true,
                open: function(event, ui) {
                    $('#'+ext+'username').focus();
                },
                close: function(event, ui) {
                    $.validationEngine.closePrompt('.formError');
                },
                dragStart: function(event, ui) {
                    $.validationEngine.closePrompt('.formError');
                }
            });
        }

        $('#'+this.dialog3).dialog('open');
    }, // init

    login: function() {
        var ext    = this.ext;
        var dialog = this.dialog3;
        var form   = this.form3;

        if (!$('#'+form).validationEngine({ returnIsValid:true })) {
            return false;
        }

        $.ajax({
            type: 'POST',
            url: $('#'+form).attr('action'),
            data: $('#'+form).serialize(),
            dataType: 'json',
            beforeSend: function () {
                $('#'+form+' button').button('disable');
                $('#'+form+' .formMessage').removeClass('green red bold').addClass('loading').html('<i>'+__('Logging..')+'</i>');
            },
            complete: function () {
                $('#'+form+' button').button('enable');
                $('#'+form+' .formMessage').removeClass('loading');
            },
            success: function (json) {
                if (json.status) {
                    $('#'+ext+'id').val(json.userid);
                    $('#'+form+' .formMessage').addClass('green bold').html(json.mesg);

                    user.username = $('#'+ext+'username').val();
                    setTimeout(function(){
                        $('#'+dialog).dialog('close');
                        $('#'+form+' .formMessage').html('');
                    }, 800);
                } else {
                    var msg = (json.mesg) ? json.mesg : '';
                    $('#'+form+' .formMessage').addClass('red bold').html(msg);
                    $('#'+ext+'username').select();
                }
            },
            error: function () {
                $('#'+form+' .formMessage').removeClass('loading').html('');
                message('Error found while in logging..', 'error');
            }
        });

        return false;
    }, // login

    cancel: function() {
        $('.mainButton').remove();
        $('#content').html('');
    }, // cancel

    logout: function() {
        $.ajax({
            type: 'GET',
            url: _webroot+'/users/logout',
            dataType: 'json',
            success: function (json) {

            }
        });

        $('#'+this.ext+'id').val('');
        this.init();
    } // logout
};

function walkIn () {
    if (!$('.ui-dialog #checkin-wizard').length) {
        $('#checkin-wrap').validationEngine();

        $('#checkin-wizard').dialog({
            width: 'auto',
            resizable: false,
            zIndex: 100,
            open: function(event, ui) {
                $('#room_type_id').focus();
            },
            close: function(event, ui) {
                _step = 1;
                $('#checkin-back-btn').button('disable');
                $.validationEngine.closePrompt('.formError');
                $('.linkselectContainer').hide();
            },
            dragStart: function(event, ui) {
                $.validationEngine.closePrompt('.formError');
                $('.linkselectContainer').hide();
            }
        });

        $('#checkout-date').datepicker({
            dateFormat: 'dd-mm-yy',
            defaultDate: +1,
            minDate: +1,
            altField: '#showDay',
            altFormat: 'DD'
        });
    }

    $('#checkin-wizard').dialog('open');
} // walkIn

function saveWalkin () {
    if (!$('#WalkinSaveForm').validationEngine({ returnIsValid:true })) {
        return false;
    }

    $.ajax({
        type: 'POST',
        url: _webroot+'/reservations/save',
        data: $('#WalkinSaveForm').serialize(),
        dataType: 'json',
        beforeSend: function () {
            $('#WalkinSaveForm button').button('disable');
            $('#WalkinSaveForm .formMessage').removeClass('green red bold').addClass('loading').html('<i>'+__('Saving..')+'</i>');
        },
        complete: function () {
            $('#WalkinSaveForm button').button('enable');
            $('#WalkinSaveForm .formMessage').removeClass('loading');
        },
        success: function (json) {
            var msg = (json.mesg) ? json.mesg : '';

            if (json.status) {
                $('#WalkinSaveForm .formMessage').addClass('green bold').html(msg);
                setTimeout(function(){
                    $('#walkin-guest-folio').dialog('close');
                    $('#WalkinSaveForm .formMessage').html('');
                }, 1000);
            } else {
                $('#WalkinSaveForm .formMessage').addClass('red bold').html(msg);
            }
        },
        error: function () {
            message(__('Error found while in saving..'), 'error');
        }
    });

    return false;
} // saveWalkin

function checkinNext () {
    if (_step == 1) {
        if (!$('#checkin-wrap').validationEngine({returnIsValid:true})) {
            return;
        };

        $('#checkin-back-btn').button('enable');
        $.ajax({
            type: 'POST',
            url: _webroot+'/room_types/checkRoom',
            data: 'type='+$('#room_type_id').val()+'&date='+$('#checkout-date').val(),
            dataType: 'json',
            beforeSend: function () {
                $('#checkin-mesg').removeClass('red bold').html('<i>checking room availability..</i>');
                $('#room-number').val('').attr('disabled', 'disabled');
            },
            complete: function () {
                $('#room-number').removeAttr('disabled');
            },
            success: function (json) {
                if (json.status) {
                    var i = 1;

                    jQuery.each(json.rooms, function() {
                        var val = this;
                        if (i == 1) {
                            $('#room-number').val(val.number);
                        }
                        i++;
                    });

                    $('#wi-nights').val(json.nights);
                    $('#checkin-mesg').html('');
                } else {
                    $('#checkin-mesg').addClass('red bold').html(json.mesg);
                }
            },
            error: function () {
                $('#checkin-mesg').addClass('red bold').html('<i>Error found while in checking..</i>');
            }
        });
    } else if (_step == 2) {
        if ($('#room-number').attr('disabled')) { // patient, wait until load completed
            return;
        }

        $('#checkin-wizard').dialog('close');
        openWalkinFolio();

        _step = 1;
        return;
    }

    next('checkin-wrap', _step);
    _step++;
} // checkinNext

function checkinBack () {
    if (_step <= 1) {
        return;
    } else if (_step == 2) {
        $('#checkin-back-btn').button('disable');
    }

    prev('checkin-wrap', _step);
    _step--;
} // checkinBack

function openWalkinFolio () {
    var ext = 'wi-';

    if (!$('.ui-dialog #walkin-guest-folio').length) {
        $('#WalkinSaveForm').validationEngine();

        $('#walkin-guest-folio').dialog({
            width: 'auto',
            position: ['center', 30],
            resizable: false,
            zIndex: 100,
            close: function(event, ui) {
                $.validationEngine.closePrompt('.formError');
                clearForm('WalkinSaveForm');
            },
            dragStart: function(event, ui) {
                $.validationEngine.closePrompt('.formError');
            }
        });

        var nights = $('#'+ext+'nights').val();
        $('#'+ext+'check-out_date').datepicker({
            dateFormat: 'dd-mm-yy',
            defaultDate: +1,
            minDate: +1,
            altField: '#'+ext+'showDay',
            altFormat: 'DD'
        }).change(function(){
            changeStayNights(ext);
        });
        $('#'+ext+'nights').change(function(){
            changeDate(ext, '+', 'check-in_date', 'check-out_date', 'showDay');
        });

        $('#'+ext+'override-rate').click(function(){ // whether to override rate?
            share.toggleOverrideRate(ext);
        }).focus(function(){
            if ($('#'+ext+'weekend').attr('disabled')) {
                $('#'+ext+'title').select();
            } else {
                $('#'+ext+'weekend').select();
            }
        });
        $('#'+ext+'weekday').change(function(){
            if ($('#'+ext+'weekend').val() == '0.00') {
                var value = number_format($(this).val(), 2);
                $('#'+ext+'weekend').val(value);
            }
        });
    }

    var dateObj    = new Date();
    var curr_date  = dateObj.getDate();
    var curr_month = dateObj.getMonth() + 1;
    var curr_year  = dateObj.getFullYear();
    var roomNumber = $('#room-number').val();
    var rt_id      = $('#room_type_id').val();

    curr_date  = (curr_date < 10) ? '0'+curr_date : curr_date;
    curr_month = (curr_month < 10) ? '0'+curr_month : curr_month;
    $('#walkin-room-number').html(roomNumber);
    $('#'+ext+'room_number').val(roomNumber);
    $('#walkin-room-type').html(_roomCodes[rt_id]+' - '+_roomTypes[rt_id]);
    $('#'+ext+'room_type_id').val($('#room_type_id').val());
    $('#'+ext+'check-in_date').val(curr_date+'-'+curr_month+'-'+curr_year);
    $('#'+ext+'checkInDay').val(_weekdays[dateObj.getDay()]);
    $('#'+ext+'check-out_date').val($('#checkout-date').val());
    $('#'+ext+'rooms').val(1);
    $('#'+ext+'showDay').val($('#showDay').val());
    $('#'+ext+'adult').val($('#checkin-adults').val());
    $('#'+ext+'child').val($('#checkin-children').val());

    share.roomRate(ext);
    $('#walkin-guest-folio').dialog('open');
    $('#WalkinSaveForm #'+ext+'title').focus();
} // openWalkinFolio


function availableRooms () {
    if (!$('.ui-dialog #available-room').length) {
        $('#available-room').dialog({
            width: 'auto',
            resizable: false,
            open: function(event, ui) {
                //$('#').focus();
            },
            close: function(event, ui) {
                $.validationEngine.closePrompt('.formError');
            },
            dragStart: function(event, ui) {
                $.validationEngine.closePrompt('.formError');
            }
        });

        $('#ar-checkoutDate').datepicker({
            dateFormat: 'dd-mm-yy',
            defaultDate: +1,
            minDate: +1
        });
    }

    $('#ar-checkoutDate').val($('#checkout-date').val());
    $('#ar-adults').val($('#checkin-adults').val());
    $('#ar-children').val($('#checkin-children').val());

    $('#available-room').dialog('open');
    checkAvailablity();
} // availableRooms

function checkAvailablity () {
    if (!$('#ar-checkoutDate').val()) {
        $.validationEngine.buildPrompt('#ar-checkoutDate', __('Please enter Checkout Date'), 'error');
        return;
    }

    loadContent('ar-grid-list-body', {
        url: _webroot+'/room_types/checkRooms',
        data: 'type='+$('#room_type_id').val()+'&date='+$('#ar-checkoutDate').val()+'&adults='+$('#ar-adults').val(),
        complete: function(){
            //
        },
        beforeSend: function () {
            $('#ar-grid-list-body').html('<div class="gridStatus"><i>'+__('checking..')+'</i></div>');
        }
    });
} // checkAvailablity

function selectRoom (room_id, room_no) {
    $('#checkout-date').val($('#ar-checkoutDate').val());
    $('#checkin-adults').val($('#ar-adults').val());
    $('#checkin-children').val($('#ar-children').val());
    $('#wi-nights').val($('#ar-night').val());

    $('#room-number').val(room_no);
    $('#available-room').dialog('close');
} // selectRoom

var reservation = {
    ext: 'rsv-',
    dialog1: 'reservation-wrap',
    dialog2: 'reservation-form-wrap',
    dialog3: 'reservation-total-stay-wrap',
    dialog4: 'reservation-assign-rooms-wrap',
    form_name: 'ReservationSaveForm',
    grid_name: 'reservationlist',
    grid_name2: 'available-rooms-list',
    grid_name3: 'assigned-rooms-list',
    opener: false,

    open: function() {
        if (!$('.ui-dialog #'+this.dialog1).length) {
            reservation.grid();

            var grid_name = this.grid_name;
            $('#'+this.dialog1).dialog({
                width: 'auto',
                resizable: false,
                close: function(evet, ui){
                    setTimeout(function(){
                        $('#'+grid_name+' tr[class*=\'trSelected\']').removeClass('trSelected');
                    }, 800);
                }
            });

            return;
        }

        $('#'+this.dialog1).dialog('open');
    }, // open

    grid: function() {
        $('#'+this.grid_name).flexigrid({
            url: _webroot+'/reservations/listing',
            dataType: 'json',
            colModel: [
                { display: 'Conf #', name: 'id', width: 40, sortable: true, align: 'right' },
                { display: 'Full name', name: 'fullname', width: 80, sortable: true, align: 'left' },
                { display: 'City, State', name: 'location', width: 80, sortable: true, align: 'left' },
                { display: 'Status', name: 'status', width: 60, sortable: true, align: 'left' },
                { display: 'CheckIn', name: 'check-in', width: 60, sortable: true, align: 'left' },
                { display: 'Room', name: 'room', width: 60, sortable: true, align: 'left' },
                { display: 'Rms', name: 'rms', width: 60, sortable: true, align: 'right' },
                { display: 'Hold', name: 'hold', width: 60, sortable: true, align: 'left' },
                { display: 'Reference', name: 'reference', width: 100, sortable: true, align: 'left' },
                { display: 'Deposit', name: 'deposit', width: 60, sortable: true, align: 'right' },
                { display: 'Arrival Time', name: 'arrival_time', width: 60, sortable: true, align: 'left' },
                { display: 'Creation', name: 'created', width: 100, sortable: true, align: 'center', hide: true },
                { display: 'Date Modified', name: 'modified', width: 100, sortable: true, align: 'center', hide: true },
                { display: 'Act', name: 'actions', width: 52, align: 'center' }
            ],
            buttons: [
                { name: 'Add Reservation', bclass: 'add', onpress: function(name){ reservation.form(name); } },
                { separator: true }
            ],
            searchitems: [
                { display: 'ID', name: 'id' },
                { display: 'Full Name', name: 'fullname' },
                { display: 'City, State', name: 'location' },
                { display: 'CheckIn', name: 'check-in' },
                { display: 'Hold', name: 'hold' },
                { display: 'Deposit', name: 'deposit' }
            ],
            sortname: 'id',
            sortorder: 'asc',
            usepager: true,
            useRp: true,
            rp: 15,
            resizable: true,
            showTableToggleBtn: true,
            width: 780,
            height: 300
        });
    }, // grid

    grid2: function(grid_url2) {
        var ext        = this.ext;
        var grid_name2 = this.grid_name2;
        var grid_name3 = this.grid_name3;

        $('#'+grid_name3).jqGrid({
            datatype: 'clientSide',
            colNames:['Room', 'Type', 'Description', 'Attributes', 'By', 'Entered', 'Cnn'],
            colModel :[
                { name:'room', index:'room', width:50, sorttype:'int' },
                { name:'type', index:'type', width:40, sorttype:'text', hidden:true },
                { name:'desc', index:'desc', width:200, sorttype:'text', hidden:true },
                { name:'attr', index:'attr', width:80, sorttype:'text', hidden:true },
                { name:'by', index:'by', width:40, sorttype:'text' },
                { name:'entered', index:'entered', width:80, sorttype:'date', datefmt:'d/m/Y' },
                { name:'cnn', index:'cnn', width:60, sorttype:'text' }
            ],
            width: 250,
            height: 160,
            rowNum: -1,
            shrinkToFit: false
        });

        $('#'+grid_name2).jqGrid({
            url: grid_url2,
            datatype: 'json',
            colNames:['Room', 'Type', 'Description', 'Attributes'],
            colModel :[
                { name:'room', index:'room', width:50, sorttype:'int' },
                { name:'type', index:'type', width:40, sorttype:'text' },
                { name:'desc', index:'desc', width:200, sorttype:'text' },
                { name:'attr', index:'attr', width:80, sorttype:'text' }
            ],
            loadComplete: function(xhr) {
                var availableIds = $('#'+grid_name2).getDataIDs();
                var assignedIds  = $('#'+grid_name3).getDataIDs();

                if (availableIds.length == 0) {
                    $('#'+ext+'assign-btn').button('disable');
                    return;
                }
                if (assignedIds.length == 0) {
                    $('#'+ext+'unassign-btn').button('disable');
                    return;
                }

                $.each(availableIds, function(){
                    var id = this+'';
                    if ($.inArray(id, assignedIds) >= 0) {
                        $('#'+grid_name2).delRowData(this);
                    }
                });
            },
            gridComplete: function() {
                var f = $('#'+grid_name2).getDataIDs();

                if (f.length == 0) {
                    $('#'+ext+'assign-btn').button('disable');
                } else {
                    var id = f.slice(0, 1);
                    $('#'+grid_name2).setSelection(id);
                    $('#'+ext+'assign-btn').button('enable');
                }
            },
            width: 390,
            height: 220,
            rowNum: -1,
            shrinkToFit: false
        });
    }, // grid2

    gridStatus: function(grid_name, btn) {
        var f = $('#'+grid_name).getDataIDs();

        if (f.length == 0) { // no more row left
            $('#'+this.ext+btn).button('disable');
        } else { // has row(s) in the list
            var id = $('#'+grid_name).jqGrid('getGridParam','selrow');

            if (!id) { // must select 1 row if any
                var id = f.slice(0, 1);
                $('#'+grid_name).setSelection(id);
            }

            $('#'+this.ext+btn).button('enable');
        }

        var rooms    = parseInt($('#'+this.ext+'rooms').val());
        var assigned = $('#'+this.grid_name3).getDataIDs();
        var unassign = rooms - assigned.length;

        if (btn == 'removeAssign-btn') { // room assigned, update form record
            if (assigned.length > 0) {
                var roomsNum   = new Array();
                var grid_name3 = this.grid_name3;

                $.each(assigned, function(){
                    roomsNum.push($('#'+grid_name3).getCell(this, 'room'));
                });
                $('#'+this.ext+'assigned').text(roomsNum.join(', '));
            } else {
                $('#'+this.ext+'assigned').text('');
            }
        }
        if (unassign == 0) {
            $('#'+this.ext+'assign-btn').button('disable');
        } else if (unassign > 0 && ($('#'+this.grid_name2).getDataIDs().length > 0)) {
            $('#'+this.ext+'assign-btn').button('enable');
        }

        if ($('#'+this.grid_name3).getDataIDs().length == 0) { // no room assigned, allow selection of room type
            $('#'+this.ext+'room_type_id').linkselect('disable', false);
        } else {  // has room assigned, disallow selection of room type
            $('#'+this.ext+'room_type_id').linkselect('disable', true);
        }

        $('#'+this.ext+'rm-assigned').text(assigned.length);
        $('#'+this.ext+'rm-unassigned').text(unassign);
    }, // gridStatus

    availability: function() {
        var error = false;

        if (!$('#'+this.ext+'check-in_date').val()) {
            $.validationEngine.buildPrompt('#'+this.ext+'check-in_date', __('Please enter Check-In Date'), 'error');
            error = true;
        }
        if (!$('#'+this.ext+'check-out_date').val()) {
            $.validationEngine.buildPrompt('#'+this.ext+'check-out_date', __('Please enter Check-Out Date'), 'error');
            error = true;
        }

        if (error) {
            return;
        }

        var form_name = this.form_name;
        var ext       = this.ext;
        var rooms     = parseInt($('#'+ext+'rooms').val());

        $.ajax({
            type: 'POST',
            url: _webroot+'/room_types/checkRoom',
            data: 'type='+$('#'+ext+'room_type_id').val()+'&date[]='+$('#'+ext+'check-in_date').val()+'&date[]='+$('#'+ext+'check-out_date').val()+'&adults='+$('#'+ext+'adult').val(),
            dataType: 'json',
            beforeSend: function () {
                $('#'+form_name+' button').button('disable');
                $('#'+ext+'availability').removeClass('ok notOk').addClass('checking');
            },
            complete: function(){
                $('#'+ext+'availability').removeClass('checking');
                $('#'+form_name+' button').button('enable');
            },
            success: function(json) {
                var msg = '';
                if (json.status && json.rooms.length >= rooms) {
                    $('#'+ext+'availability').addClass('ok');
                    $('#'+form_name+' .formMessage').addClass('green bold').html(__('Room available!'));
                } else {
                    $('#'+ext+'availability').addClass('notOk');
                    $('#'+form_name+' .formMessage').addClass('red bold').html(__('Room unavailable..'));
                }

                setTimeout(function(){
                    $('#'+form_name+' .formMessage').removeClass('green red bold').html('');
                }, 2000);
            },
            error: function() {
                message(__('Error found while in checking..'), 'error');
            }
        });
    }, // availability

    assignRooms: function() {
        var grid_url2 = _webroot+'/room_types/availableRooms/'+$('#'+this.ext+'room_type_id').val()+'/'+$('#'+this.ext+'check-in_date').val()+'/'+$('#'+this.ext+'check-out_date').val()+'/';

        if (!$('.ui-dialog #'+this.dialog4).length) { // Initialize Assign Rooms dialog
            reservation.grid2(grid_url2);

            var grid = this.grid2;
            $('#'+this.dialog4).dialog({
                width: 'auto',
                resizable: false,
                close: function(evet, ui){
                    setTimeout(function(){

                    }, 800);
                }
            });
        } else {
            /*var f = $('#'+this.grid_name3).getDataIDs();

            if (f.length > 0) {
                grid_url2 += f.join(',')+'/';
            }*/

            $('#'+this.grid_name2).setGridParam({ url:grid_url2 });
            $('#'+this.grid_name2).trigger('reloadGrid');
        }

        var rooms = $('#'+this.ext+'rooms').val();
        $('#'+this.ext+'rm-reserved').text(rooms);
        $('#'+this.ext+'rm-unassigned').text(rooms);
        $('#'+this.dialog4).dialog('open');
    }, //assignRooms

    assign: function() {
        var id = $('#'+this.grid_name2).jqGrid('getGridParam','selrow');
        var dt = $('#'+this.grid_name2).getRowData(id);

        var rw = {
            room: dt.room,
            type: dt.type,
            desc: dt.desc,
            attr: dt.attr,
            by: 'Me',
            entered: getDate('today'),
            cnn: ''
        };

        if ($('#'+this.grid_name3).addRowData(id, rw)) {
            //$('#'+this.grid_name3).sortGrid('room', false);
            this.gridStatus(this.grid_name3, 'removeAssign-btn');

            if ($('#'+this.grid_name2).delRowData(id)) {
                this.gridStatus(this.grid_name2, 'assign-btn');
            }
        }
    }, // assign

    removeAssign: function() {
        var id = $('#'+this.grid_name3).jqGrid('getGridParam','selrow');
        var dt = $('#'+this.grid_name3).getRowData(id);

        var rw = {
            room: dt.room,
            type: dt.type,
            desc: dt.desc,
            attr: dt.attr
        };

        if ($('#'+this.grid_name2).addRowData(id, rw)) {
            //$('#'+this.grid_name2).sortGrid('room', false);
            this.gridStatus(this.grid_name2, 'assign-btn');

            if ($('#'+this.grid_name3).delRowData(id)) {
                this.gridStatus(this.grid_name3, 'removeAssign-btn');
            }
        }
    }, // removeAssign

    totalStay: function() {
        if (!$('.ui-dialog #'+this.dialog3).length) {
            var dialog3 = this.dialog3;
            $('#'+dialog3).dialog({
                width: 'auto',
                resizable: false,
                modal: true,
                open: function(event, ui) {
                    $('#'+dialog3+' button[type=button]').focus();
                }
            });
            share.rateDetailsGrid();
        }

        var tid = $('#'+this.ext+'room_type_id').val();
        var rcd = '';

        if ($('#'+this.ext+'rate_code').val()) {
            rcd = $('#'+this.ext+'rate_code').val()+' - '+$('#'+this.ext+'rate_desc').html();
        }

        $('#'+this.ext+'checkin-txt').text($('#'+this.ext+'check-in_date').val());
        $('#'+this.ext+'checkin-day-txt').text($('#'+this.ext+'checkInDay').val());
        $('#'+this.ext+'nights-txt').text($('#'+this.ext+'nights').val());
        $('#'+this.ext+'checkout-txt').text($('#'+this.ext+'check-out_date').val());
        $('#'+this.ext+'checkout-day-txt').text($('#'+this.ext+'showDay').val());
        $('#'+this.ext+'roomType-txt').text($('#'+this.ext+'rooms').val()+' ('+_roomTypes[tid]+')');
        $('#'+this.ext+'rateCode-txt').text(rcd);
        $('#'+this.ext+'discount-txt').text($('#'+this.ext+'discount').val());
        $('#'+this.dialog3).dialog('open');

        share.rateDetails(this.ext);
    }, // totalStay

    form: function(act) {
        var ext       = this.ext;
        var form_name = this.form_name;
        var grid_name = this.grid_name;

        if (!$('.ui-dialog #'+this.dialog2).length) {
            $('#'+this.dialog2).dialog({
                width: 'auto',
                resizable: false,
                modal: true,
                open: function(event, ui) {
                    $('#'+ext+'title').focus();
                },
                close: function(event, ui) {
                    $.validationEngine.closePrompt('.formError');
                    $('#'+form_name+' .formMessage').html('');
                    $('#'+grid_name+' tr[class*=\'trSelected\']').removeClass('trSelected');
                },
                dragStart: function(event, ui) {
                    $.validationEngine.closePrompt('.formError');
                }
            });

            $('#'+ext+'check-in_date').datepicker({
                dateFormat: 'dd-mm-yy',
                defaultDate: 0,
                minDate: 0,
                altField: '#'+ext+'checkInDay',
                altFormat: 'DD'
            }).change(function(){
                changeDate(ext, '+', 'check-in_date', 'check-out_date', 'showDay');
            });
            $('#'+ext+'check-out_date').datepicker({
                dateFormat: 'dd-mm-yy',
                defaultDate: +1,
                minDate: +1,
                altField: '#'+ext+'showDay',
                altFormat: 'DD'
            }).change(function(){
                changeDate(ext, '-', 'check-out_date', 'check-in_date', 'checkInDay');
            });
            $('#'+ext+'nights').change(function(){
                changeDate(ext, '+', 'check-in_date', 'check-out_date', 'showDay');
            });

            $('#'+ext+'room_type_options_td').click(function(){ // show Room Type options disabled warning when user has assigned any room
                if ($('#'+form_name+' span.linkselectDisabled').length > 0) {
                    var msg = '<p>'+__('Problem: You cannnot change the room type on this reservation because there are assigned rooms on this reservation.')+'</p>' +
                              '<p>'+__('Assigned rooms on a reservation should only be for the room type selected.')+'</p>' +
                              '<p>'+__('Solution: If you want to change the room type, you must first select the Assign Room button and remove any assigned rooms. ' +
                              'Once you have removed the rooms, you can then select another room type.')+'</p>' +
                              '<p>'+__('A separate reservation must be made for each room type.')+'</p>';
                    message(msg);
                }
            });

            $('#'+ext+'override-rate').click(function(){ // whether to override rate?
                share.toggleOverrideRate(ext);
            }).focus(function(){
                if ($('#'+ext+'weekend').attr('disabled')) {
                    $('#'+ext+'title').select();
                } else {
                    $('#'+ext+'weekend').select();
                }
            });
            $('#'+ext+'weekday').change(function(){
                if ($('#'+ext+'weekend').val() == '0.00') {
                    var value = number_format($(this).val(), 2);
                    $('#'+ext+'weekend').val(value);
                }
            });

            $('#'+form_name+' button.assignRoom').button('option', 'icons', { primary:'ui-icon-assignRoom' });
            $('#'+form_name).validationEngine();
        }

        if (act != 'edit') { // create new record
            clearForm(form_name);
            $('#'+ext+'check-in_date').val(getDate('today'));
            $('#'+ext+'checkInDay').val(getDate('day'));
            $('#'+ext+'check-out_date').val(getDate('tomorrow'));
            $('#'+ext+'showDay').val(getDate('tomorrow day'));
            $('#'+ext+'rooms').val(1);
            $('#'+ext+'nights').val(1);
            $('#'+ext+'adult').val(1);
            $('#'+ext+'child').val(0);
            $('#'+ext+'room_type_id').linkselect('val', _defRoomTypeId);
            $('#'+ext+'discount').val('0.00');
            $('#'+ext+'created').html('Created '+date('l, F d, Y h:i A')+' by '+user.username);
            share.roomRate(ext);
        }

        $('#'+this.dialog2).dialog('open');
    }, // form

    save: function() {
        var ext       = this.ext;
        var dialog2   = this.dialog2;
        var form_name = this.form_name;
        var grid_name = this.grid_name;

        if (!$('#'+form_name).validationEngine({ returnIsValid:true })) {
            return false;
        }

        $.ajax({
            type: 'POST',
            url: $('#'+form_name).attr('action'),
            data: $('#'+form_name).serialize(),
            dataType: 'json',
            beforeSend: function () {
                $('#'+form_name).attr('disabled', 'disabled');
                $('#'+form_name+' button').button('disable');
                $('#'+form_name+' .formMessage').removeClass('green red bold').addClass('loading').html('<i>'+__('Saving..')+'</i>');
            },
            complete: function () {
                $('#'+form_name).removeAttr('disabled');
                $('#'+form_name+' button').button('enable');
                $('#'+form_name+' .formMessage').removeClass('loading');
            },
            success: function (json) {
                if (json.status) {
                    $('#'+grid_name).flexReload();
                    $('#'+form_name+' .formMessage').addClass('green bold').html(json.mesg);
                    setTimeout(function(){
                        $('#'+dialog2).dialog('close');
                        $('#'+form_name+' .formMessage').html('');
                    }, 1000);
                } else {
                    if ($.isArray(json.error)) {
                        jQuery.each(json.error, function() {
                            $.validationEngine.buildPrompt('#'+ext+this.f, this.m, 'error');
                        });
                    }

                    var msg = (json.mesg) ? json.mesg : '';
                    $('#'+form_name+' .formMessage').addClass('red bold').html(msg);
                }
            },
            error: function () {
                $('#'+form_name+' .formMessage').html('');
                message(__('Error found while in saving..'), 'error');
            }
        });

        return false;
    }, //save

    edit: function(id) {
        var data = selectRecord(this.dialog1, id);

        if (!$.isArray(data.fields) || !$.isArray(data.values)) {
            return;
        }

        populate(this.ext, data);
        this.form('edit');
    }, // edit

    select: function(id) {

    }, // select

    update: function(act) {
        var ids = selectedRows(this.grid_name);
        var act = act.toLowerCase();
        var msg = '';

        if (ids.length == 0) {
            message(str_replace('{action}', act, __('Please select the row that want to {action}.')));
            return;
        } else if (ids.length > 1) {
            msg = str_replace(['{action}', '{no}'], [act, ids.length], __('Are you sure you want to {action} these {no} selected records?'));
            ids = ids.join(',');
        } else if (ids.length == 1) {
            msg = str_replace('{action}', act, __('Are you sure you want to {action} this selected record?'));
            ids = ids[0];
        }

        if (!confirm(msg)) {
            return;
        }

        var grid_name = this.grid_name;
        var dialog1   = this.dialog1;
        var statusTxt = '';

        $.ajax({
            type: 'POST',
            url: _webroot+'/hotels/update/',
            data: 'id='+ids+'&task='+act,
            dataType: 'json',
            beforeSend: function() {
                statusTxt = $('#'+dialog1+' span.pPageStat').html();

                $('#'+dialog1+' span.pPageStat').text(__('Processing, please wait ...'));
                $('#'+dialog1+' div.pReload').addClass('loading');
            },
            success: function(json) {
                if (json.status) {
                    $('#'+grid_name).flexReload();
                } else if (json.mesg) {
                    $('#'+dialog1+' span.pPageStat').html(statusTxt);
                    $('#'+dialog1+' div.pReload').removeClass('loading');
                    message(json.mesg, 'error');
                }
            },
            error: function() {
                message(__('Error found while in updating'), 'error');
            }
        });
    }
};

var share = {
    ext: 'shr-',
    dialog1: 'display-rate-wrap',
    grid_name1: 'displayRateList',
    grid_name2: 'rateDetailsList',
    opener: false,

    roomRate: function(ext) {
        if ($('#'+ext+'override-rate').attr('checked')) {
            return;
        }

        var adult    = $('#'+ext+'adult').val();
        var roomType = $('#'+ext+'room_type_id').val();
        var checkin  = $('#'+ext+'check-in_date').val();
        var aryDate  = split('-', checkin);
        var weekday  = 0;
        var weekend  = 0;
        var rateId   = '';
        var rateCdId = '';
        var rateCode = '';
        var rateDesc = '';

        var checkinTime = strtotime(aryDate[2]+'-'+aryDate[1]+'-'+aryDate[0]);

        $.each(_rates, function(){
            if (roomType == this.room_type_id) {
                if (checkinTime >= this.from_time && checkinTime <= this.to_time) {
                    if (adult <= 1) {
                        weekday = this.d_1;
                        weekend = this.e_1;
                    } else if (adult == 2) {
                        weekday = this.d_2;
                        weekend = this.e_2;
                    } else if (adult == 3) {
                        weekday = this.d_3;
                        weekend = this.e_3;
                    } else if (adult >= 4) {
                        weekday = this.d_4;
                        weekend = this.e_4;
                    }

                    rateId   = this.id;
                    rateCdId = this.rate_code_id;
                    rateCode = this.rate_code;
                    rateDesc = this.description;
                }
            }
        });

        $('#'+ext+'rate_id').val(rateId);
        $('#'+ext+'rate_code_id').val(rateCdId);
        $('#'+ext+'rate_code').val(rateCode);
        $('#'+ext+'rate_desc').text(rateDesc);
        $('#'+ext+'weekday').val(number_format(weekday, 2));
        $('#'+ext+'weekend').val(number_format(weekend, 2));
    }, // roomRate

    toggleOverrideRate: function(ext) {
        if ($('#'+ext+'override-rate').attr('checked')) {
            $('#'+ext+'weekday').removeAttr('disabled').val('0.00').focus().select();
            $('#'+ext+'weekend').removeAttr('disabled').val('0.00');
            $('#'+ext+'rate_code').val('').attr('disabled', 'disabled');
            $('#'+ext+'rate_desc').text(__('(Rate Overridden)'));
        } else {
            $('#'+ext+'weekday').attr('disabled', 'disabled');
            $('#'+ext+'weekend').attr('disabled', 'disabled');
            $('#'+ext+'rate_code').removeAttr('disabled').focus().select();
            $('#'+ext+'rate_desc').text('');
            this.roomRate(ext);
        }
    }, // toggleOverrideRate

    displayRate: function(ext) {
        if ($('#'+ext+'override-rate').attr('checked')) {
            return;
        }

        if (!$('.ui-dialog #'+this.dialog1).length) {
            share.rateGrid(ext);

            var grid_name = this.grid_name;
            $('#'+this.dialog1).dialog({
                width: 'auto',
                modal: true,
                resizable: false,
                close: function(evet, ui){
                    setTimeout(function(){
                        //$('#'+grid_name+' tr[class*=\'trSelected\']').removeClass('trSelected');
                    }, 800);
                }
            });
        }

        var adult    = $('#'+ext+'adult').val();
        var roomType = $('#'+ext+'room_type_id').val();
        var checkIn  = $('#'+ext+'check-in_date').val();
        var checkOut = $('#'+ext+'check-out_date').val();
        var aryDate  = split('-', checkIn);
        var aryDate2 = split('-', checkOut);
        var weekday  = 0;
        var weekend  = 0;
        var addTime  = 0;
        var total    = 0;
        var newrow   = '';
        var newRows  = new Array();

        var checkInTime  = strtotime(aryDate[2]+'-'+aryDate[1]+'-'+aryDate[0]);
        var checkOutTime = strtotime(aryDate2[2]+'-'+aryDate2[1]+'-'+aryDate2[0]);

        $.each(_rates, function(){
            if (this.room_type_id == 0 || roomType == this.room_type_id) {
                if (checkInTime >= this.from_time && checkInTime <= this.to_time) {
                    if (adult <= 1) {
                        weekday = this.d_1;
                        weekend = this.e_1;
                    } else if (adult == 2) {
                        weekday = this.d_2;
                        weekend = this.e_2;
                    } else if (adult == 3) {
                        weekday = this.d_3;
                        weekend = this.e_3;
                    } else if (adult >= 4) {
                        weekday = this.d_4;
                        weekend = this.e_4;
                    }

                    addTime = checkInTime;
                    total   = 0;
                    newrow  = {
                        id: this.id,
                        room_type: this.room_type_code,
                        rate_code_id: this.rate_code_id,
                        rate_code: this.rate_code,
                        desc: this.description,
                        weekday: weekday,
                        weekend: weekend,
                        changes: ''
                    };

                    while (addTime < checkOutTime) { // load all staying nights
                        var day = date('l', addTime);

                        if (addTime > this.to_time) {
                            var rate_code = this.rate_code;
                            var room_type = this.room_type_id;

                            $.each(_rates, function(){
                                if (addTime >= this.from_time && addTime <= this.to_time && rate_code == this.rate_code && room_type == this.room_type_id) { // rate changed with same rate code & room type
                                    if (newrow.changes.length == 0) {
                                        newrow.changes = 'Starts on '+date('d/m/Y', addTime);
                                    }

                                    if (adult <= 1) {
                                        total += (day == 'Friday' || day == 'Saturday') ? parseFloat(this.e_1) : parseFloat(this.d_1);
                                    } else if (adult == 2) {
                                        total += (day == 'Friday' || day == 'Saturday') ? parseFloat(this.e_2) : parseFloat(this.d_2);
                                    } else if (adult == 3) {
                                        total += (day == 'Friday' || day == 'Saturday') ? parseFloat(this.e_3) : parseFloat(this.d_3);
                                    } else if (adult >= 4) {
                                        total += (day == 'Friday' || day == 'Saturday') ? parseFloat(this.e_4) : parseFloat(this.d_4);
                                    }
                                }
                            });
                        } else {
                            if (adult <= 1) {
                                total += (day == 'Friday' || day == 'Saturday') ? parseFloat(this.e_1) : parseFloat(this.d_1);
                            } else if (adult == 2) {
                                total += (day == 'Friday' || day == 'Saturday') ? parseFloat(this.e_2) : parseFloat(this.d_2);
                            } else if (adult == 3) {
                                total += (day == 'Friday' || day == 'Saturday') ? parseFloat(this.e_3) : parseFloat(this.d_3);
                            } else if (adult >= 4) {
                                total += (day == 'Friday' || day == 'Saturday') ? parseFloat(this.e_4) : parseFloat(this.d_4);
                            }
                        }

                        addTime += 86400;
                    }

                    newrow.total = number_format(total, 2);
                    newRows.push(newrow);
                }
            }
        });

        $('#'+this.grid_name1+'').clearGridData(false);
        $('#'+this.grid_name1+'').addRowData('id', newRows);
        $('#'+this.dialog1).dialog('open');
    }, // displayRate

    rateGrid: function(ext) {
        var grid_name1 = this.grid_name1;

        $('#'+grid_name1).jqGrid({
            datatype: 'clientSide',
            colNames:['Room Type', 'Rate Code', 'Description', 'WeekDay', 'Weekend', 'Total Stay', 'Rate Changes'],
            colModel :[
                { name:'room_type', index:'room_type', width:78, sorttype:'text', align:'center' },
                { name:'rate_code', index:'rate_code', width:86, sorttype:'text' },
                { name:'desc', index:'desc', width:200, sorttype:'text' },
                { name:'weekday', index:'weekday', width:75, sorttype:'float', align:'right' },
                { name:'weekend', index:'weekend', width:75, sorttype:'float', align:'right' },
                { name:'total', index:'total', width:83, sorttype:'float', align:'right' },
                { name:'changes', index:'changes', width:148, sorttype:'text' }
            ],
            width: 780,
            height: 300,
            rowNum: -1,
            shrinkToFit: false
        });
    }, // rateGrid

    rateDetails: function(ext) {
        ad = $('#'+ext+'adult').val(); // adult
        id = $('#'+ext+'rate_id').val(); // rate id
        rc = $('#'+ext+'rate_code_id').val(); // rate code id
        rt = $('#'+ext+'room_type_id').val(); // room type id
        ro = $('#'+ext+'override-rate').attr('checked'); // rate overriden
        wd = $('#'+ext+'weekday').val(); // weekday
        we = $('#'+ext+'weekend').val(); // weekend
        t  = this._date2time(ext); // time
        a  = t.checkInTime; // add time
        b  = 0; // balance
        c  = ''; // changes
        d  = new Array(); // data

        while (a < t.checkOutTime) {
            var day = date('D', a);
            var amt = 0;

            if (ro) { // rate overriden
                amt = (day == 'Fri' || day == 'Sat') ? parseFloat(we) : parseFloat(wd);
                b  += amt;
            } else {
                $.each(_rates, function(){
                    if (!amt && id == this.id && a >= this.from_time && a <= this.to_time) {
                        amt = share._roomCharges(ad, day, this);
                        b  += amt;
                    } else if (!amt && rc == this.rate_code_id && rt == this.room_type_id && a >= this.from_time && a <= this.to_time) {
                        amt = share._roomCharges(ad, day, this);
                        b  += amt;
                        c   = __('Yes');
                    }
                });
            }

            d.push({
                post_date: date('d/m/Y D', a),
                room_amount: number_format(amt, 2),
                room_tax: '0.00',
                total_stay: number_format(amt, 2),
                balance: number_format(b, 2),
                changes: c
            });

            a += 86400;
        }

        var rooms  = $('#'+ext+'rooms').val();
        var total  = parseInt(rooms) * b;
        var stotal = total;

        $('#'+ext+'totalRoom-txt').text(number_format(total, 2));
        $('#'+ext+'subTotal-txt').text(number_format(stotal, 2));
        $('#'+ext+'total-stay').text(number_format(stotal, 2));

        $('#'+this.grid_name2).clearGridData(false).addRowData(false, d);
    }, // rateDetails

    rateDetailsGrid: function() {
        var grid_name2 = this.grid_name2;

        $('#'+grid_name2).jqGrid({
            datatype: 'clientSide',
            colNames:['Posting Date', 'Room Amount', 'Room Tax', 'Total Stay', 'Balance', 'Change'],
            colModel :[
                { name:'post_date', index:'post_date', width:128, sortable:false },
                { name:'room_amount', index:'room_amount', width:85, sortable:false, align:'right' },
                { name:'room_tax', index:'room_tax', width:80, sortable:false, align:'right' },
                { name:'total_stay', index:'total_stay', width:80, sortable:false, align:'right' },
                { name:'balance', index:'balance', width:80, sortable:false, align:'right' },
                { name:'changes', index:'changes', width:130, sortable:false }
            ],
            width: 630,
            height: 300,
            rowNum: -1,
            shrinkToFit: false
        });
    }, // rateDetailsGrid


    _roomCharges: function(adults, day, rate) { // private
        var wd  = 0;
        var we  = 0;

        if (adults <= 1) {
            wd = rate.d_1;
            we = rate.e_1;
        } else if (adults == 2) {
            wd = rate.d_2;
            we = rate.e_2;
        } else if (adults == 3) {
            wd = rate.d_3;
            we = rate.e_3;
        } else {
            wd = rate.d_4;
            we = rate.e_4;
        }

        return (day == 'Fri' || day == 'Sat') ? parseFloat(we) : parseFloat(wd);
    }, // _roomCharges

    _date2time: function(ext) { // private
        var checkIn  = $('#'+ext+'check-in_date').val();
        var checkOut = $('#'+ext+'check-out_date').val();
        var arrayIn  = split('-', checkIn);
        var arrayOut = split('-', checkOut);
        var inTime   = strtotime(arrayIn[2]+'-'+arrayIn[1]+'-'+arrayIn[0]);
        var outTime  = strtotime(arrayOut[2]+'-'+arrayOut[1]+'-'+arrayOut[0]);

        return {
            checkInTime: inTime,
            checkOutTime: outTime
        };
    } // date2time
};

function openGuestList (ext) {
    _guestOpener = ext;
    $.validationEngine.closePrompt('.formError');
    guestProfiles();
} // openGuestList

function selectGuestRecord (id) {
    var data = selectRecord('guest-profiles-wrap', id);

    if (_guestOpener) {
        populate(_guestOpener, data);
    }

    $('#guest-profiles-wrap').dialog('close');
} // selectGuestRecord

function guestProfiles () {
    if (!$('.ui-dialog #guest-profiles-wrap').length) {
        guest_grid();

        $('#guest-profiles-wrap').dialog({
            width: 'auto',
            resizable: false,
            close: function(evet, ui){
                _guestOpener = '';
                setTimeout(function(){
                    $('#guestlist tr[class*=\'trSelected\']').removeClass('trSelected');
                }, 800);
            }
        });
    }

    $('#guest-profiles-wrap').dialog('open');
} // guestProfiles

function guest_grid () {
    $("#guestlist").flexigrid({
        url: _webroot+'/guests/listing',
        dataType: 'json',
        colModel: [
            { display: 'ID', name: 'id', width: 40, sortable: true, align: 'right' },
            { display: 'Title', name: 'title', width: 40, sortable: true, align: 'left', hide: true },
            { display: 'First Name', name: 'firstname', width: 60, sortable: true, align: 'left' },
            { display: 'Last Name', name: 'lastname', width: 60, sortable: true, align: 'left' },
            { display: 'Street', name: 'street', width: 120, sortable: true, align: 'left', hide: true },
            { display: 'City', name: 'city', width: 64, sortable: true, align: 'left' },
            { display: 'State', name: 'state', width: 60, sortable: true, align: 'left' },
            { display: 'Zip Code', name: 'zip_code', width: 44, sortable: true, align: 'left' },
            { display: 'Country', name: 'country', width: 60, sortable: true, align: 'left' },
            { display: 'Phone', name: 'phone', width: 73, sortable: true, align: 'left' },
            { display: 'Email', name: 'email', width: 104, sortable: true, align: 'left' },
            { display: 'Password', name: 'password', width: 80, sortable: true, align: 'left', hide: true },
            { display: 'Last Stay', name: 'last_stay', width: 80, sortable: true, align: 'center' },
            { display: 'Creation', name: 'created', width: 100, sortable: true, align: 'center', hide: true },
            { display: 'Date Modified', name: 'modified', width: 100, sortable: true, align: 'center', hide: true },
            { display: 'Act', name: 'actions', width: 52, align: 'center' }
        ],
        buttons: [
            { name: 'Add', bclass: 'add', onpress: guestProfile },
            { separator: true },
            { name: 'Delete', bclass: 'delete', onpress: updateProfile },
            { separator: true }
        ],
        searchitems: [
            { display: 'ID', name: 'id' },
            { display: 'First Name', name: 'firstname' },
            { display: 'Last Name', name: 'lastname' },
            { display: 'Phone', name: 'phone' },
            { display: 'Email', name: 'email' }
        ],
        sortname: 'id',
        sortorder: 'asc',
        usepager: true,
        useRp: true,
        rp: 15,
        resizable: true,
        showTableToggleBtn: true,
        width: 832,
        height: 300
    });

    /*$('#guest-profiles-wrap div.pSearch').toggle(function() {
            $('#guest-profiles-wrap').dialog('option', 'height', 450);
        }, function() {
            setTimeout(function(){
                $('#guest-profiles-wrap').dialog('option', 'height', 413)
            }, 200);
        }
    );*/
} // guest_grid

function guestProfile (act) {
    if (!$('.ui-dialog #guest-profile-wrap').length) {
        clog('Initial guest profile validation form');
        init_country_ac('GuestSaveForm');
        $('#GuestSaveForm').validationEngine();
        $('#guest-profile-wrap').dialog({
            width: 'auto',
            resizable: false,
            modal: true,
            close: function(event, ui) {
                $.validationEngine.closePrompt('.formError');
                $('#guest-profile-wrap .formMessage').html('');
                $('#guestlist tr[class*=\'trSelected\']').removeClass('trSelected');
            },
            dragStart: function(event, ui) {
                $.validationEngine.closePrompt('.formError');
            }
        });

        return;
    }
    if (act != 'edit') {
        clearForm('GuestSaveForm');
    }

    $('#guest-profile-wrap').dialog('open');
} // guestProfile

function updateProfile (act) {
    var ids = selectedRows('guestlist');
    var act = act.toLowerCase();
    var msg = '';

    if (ids.length == 0) {
        message(str_replace('{action}', act, __('Please select the row that want to {action}.')));
        return;
    } else if (ids.length > 1) {
        msg = str_replace(['{action}', '{no}'], [act, ids.length], __('Are you sure you want to {action} these {no} selected records?'));
        ids = ids.join(',');
    } else if (ids.length == 1) {
        msg = str_replace('{action}', act, __('Are you sure you want to {action} this selected record?'));
        ids = ids[0];
    }

    if (!confirm(msg)) {
        return;
    }

    var grid_name = 'guestlist';
    var dialog1   = 'guest-profiles-wrap';
    var statusTxt = '';

    $.ajax({
        type: 'POST',
        url: _webroot+'/guests/update/',
        data: 'id='+ids+'&task='+act,
        dataType: 'json',
        beforeSend: function() {
            statusTxt = $('#'+dialog1+' span.pPageStat').html();

            $('#'+dialog1+' span.pPageStat').text(__('Processing, please wait ...'));
            $('#'+dialog1+' div.pReload').addClass('loading');
        },
        success: function(json) {
            if (json.status) {
                $('#'+grid_name).flexReload();;
            } else if (obj.mesg) {
                $('#'+dialog1+' span.pPageStat').html(statusTxt);
                $('#'+dialog1+' div.pReload').removeClass('loading');
                message(obj.mesg);
            }
        },
        error: function() {
            message(__('Error found while in updating'));
        }
    });
} // updateProfile

function editGuestProfile (id) {
    var data = selectRecord('guest-profiles-wrap', id);

    populate('', data);
    guestProfile('edit');
} // editGuestProfile

function saveGuestProfile () {
    clog('Save Guest Profile');

    if (!$('#GuestSaveForm').validationEngine({ returnIsValid:true })) {
        return false;
    }

    $.ajax({
        type: 'POST',
        url: $('#GuestSaveForm').attr('action'),
        data: $('#GuestSaveForm').serialize(),
        dataType: 'json',
        beforeSend: function () {
            $('#GuestSaveForm .formMessage').removeClass('green red bold').addClass('loading').html('<i>'+__('Saving..')+'</i>');
            $('#GuestSaveForm button').button('disable');
        },
        complete: function () {
            $('#GuestSaveForm button').button('enable');
            $('#GuestSaveForm .formMessage').removeClass('loading');
        },
        success: function (json) {
            if (json.status) {
                $("#guestlist").flexReload();
                $('#GuestSaveForm .formMessage').addClass('green bold').html(json.mesg);
                setTimeout(function(){
                    $('#guest-profile-wrap').dialog('close');
                    $('#GuestSaveForm .formMessage').html('');
                }, 1000);
            } else {
                if ($.isArray(json.error)) {
                    jQuery.each(json.error, function() {
                        $.validationEngine.buildPrompt('#'+this.f, this.m, 'error');
                    });
                }

                var msg = (json.mesg) ? json.mesg : '';
                $('#GuestSaveForm .formMessage').addClass('red bold').html(msg);
            }
        },
        error: function () {
            $('#GuestSaveForm .formMessage').html('');
            message(__('Error found while in saving..'), 'error');
        }
    });

    return false;
} // saveGuestProfile

function init_country_ac (parent_id) {
    $.getJSON(_webroot+'/countries/listing', function(data){
        $('#'+parent_id+' #country').autocomplete(data, {
            minChars: 1,
            max: 12,
            autoFill: true,
            mustMatch: true,
            matchContains: false,
            scrollHeight: 260
        });
    });
} // init_country_ac

var rateInfo = {
    ext: 'rr-',
    dialog1: 'rate-info-wrap',
    dialog2: 'rate-form-wrap',
    form_name: 'RateSaveForm',
    grid_name: 'ratelist',
    opener: false,

    open: function() {
        if (!$('.ui-dialog #'+this.dialog1).length) {
            rateInfo.grid();

            var grid_name = this.grid_name;
            $('#'+this.dialog1).dialog({
                width: 'auto',
                resizable: false,
                close: function(evet, ui){
                    setTimeout(function(){
                        $('#'+grid_name+' tr[class*=\'trSelected\']').removeClass('trSelected');
                    }, 800);
                }
            });

            return;
        }

        $('#'+this.dialog1).dialog('open');
    }, // open

    grid: function() {
        $('#'+this.grid_name).flexigrid({
            url: _webroot+'/rates/listing',
            dataType: 'json',
            colModel: [
                { display: 'ID', name: 'id', width: 40, sortable: true, align: 'right' },
                { display: 'Room Type Id', name: 'room_type_id', width: 40, sortable: true, align: 'right', hide: true },
                { display: 'Rate Code Id', name: 'rate_code_id', width: 60, sortable: true, align: 'right', hide: true },
                { display: 'Room Type', name: 'type', width: 60, sortable: true, align: 'center' },
                { display: 'Rate Code', name: 'code', width: 55, sortable: true, align: 'center' },
                { display: 'From', name: 'from', width: 60, sortable: true, align: 'left' },
                { display: 'To', name: 'to', width: 60, sortable: true, align: 'left' },
                { display: 'Description', name: 'description', width: 140, sortable: true, align: 'left' },
                { display: '1 Adult', name: 'd_1', width: 50, sortable: true, align: 'right' },
                { display: '1 Adult Weekend', name: 'e_1', width: 70, sortable: true, align: 'right' },
                { display: '2 Adults', name: 'd_2', width: 60, sortable: true, align: 'right', hide: true },
                { display: '2 Adults Weekend', name: 'e_2', width: 60, sortable: true, align: 'right', hide: true },
                { display: '3 Adults', name: 'd_3', width: 60, sortable: true, align: 'right', hide: true },
                { display: '3 Adults Weekend', name: 'e_3', width: 60, sortable: true, align: 'right', hide: true },
                { display: '4 Adults', name: 'd_4', width: 60, sortable: true, align: 'right', hide: true },
                { display: '4 Adults Weekend', name: 'e_4', width: 60, sortable: true, align: 'right', hide: true },
                { display: 'Extra Adult', name: 'extra_adult_weekday', width: 60, sortable: true, align: 'right', hide: true },
                { display: 'Extra Adult Weekend', name: 'extra_adult_weekend', width: 60, sortable: true, align: 'right', hide: true },
                { display: 'Extra Child', name: 'extra_child_weekday', width: 60, sortable: true, align: 'right', hide: true },
                { display: 'Extra Child Weekend', name: 'extra_child_weekend', width: 60, sortable: true, align: 'right', hide: true },
                { display: 'Creation', name: 'created', width: 100, sortable: true, align: 'center', hide: true },
                { display: 'Date Modified', name: 'modified', width: 100, sortable: true, align: 'center', hide: true },
                { display: 'Act', name: 'actions', width: 52, align: 'center' }
            ],
            buttons: [
                { name: 'Add', bclass: 'add', onpress: function(name){ rateInfo.form(name); } },
                { separator: true },
                /*{ name: 'Delete', bclass: 'delete', onpress: updateProfile },
                { separator: true }*/
            ],
            searchitems: [
                { display: 'ID', name: 'id' },
                { display: 'First Name', name: 'firstname' },
                { display: 'Last Name', name: 'lastname' },
                { display: 'Phone', name: 'phone' },
                { display: 'Email', name: 'email' }
            ],
            sortname: 'id',
            sortorder: 'asc',
            usepager: true,
            useRp: true,
            rp: 15,
            resizable: true,
            showTableToggleBtn: true,
            width: 780,
            height: 300
        });
    }, // grid

    form: function(act) {
        if (!$('.ui-dialog #'+this.dialog2).length) {
            var ext       = this.ext;
            var form_name = this.form_name;
            var grid_name = this.grid_name;

            $('#'+this.dialog2).dialog({
                width: 'auto',
                resizable: false,
                modal: true,
                open: function(event, ui) {
                    $('#'+ext+'rate_code_id').focus();
                },
                close: function(event, ui) {
                    $.validationEngine.closePrompt('.formError');
                    $('#'+form_name+' .formMessage').html('');
                    $('#'+grid_name+' tr[class*=\'trSelected\']').removeClass('trSelected');
                },
                dragStart: function(event, ui) {
                    $.validationEngine.closePrompt('.formError');
                }
            });

            $('#'+ext+'from').datepicker({
                dateFormat: 'dd-mm-yy'
            });
            $('#'+ext+'to').datepicker({
                dateFormat: 'dd-mm-yy'
            });

            $('#'+form_name).validationEngine();
        }

        if (act != 'edit') { // create new record
            clearForm(this.form_name);
            $('#'+ext+'room_type_id').linkselect('val', _defRoomTypeId);
        }

        $('#'+this.dialog2).dialog('open');
    }, // form

    save: function() {
        var ext       = this.ext;
        var dialog2   = this.dialog2;
        var form_name = this.form_name;
        var grid_name = this.grid_name;

        if (!$('#'+form_name).validationEngine({ returnIsValid:true })) {
            return false;
        }

        $.ajax({
            type: 'POST',
            url: $('#'+form_name).attr('action'),
            data: $('#'+form_name).serialize(),
            dataType: 'json',
            beforeSend: function () {
                $('#'+form_name).attr('disabled', 'disabled');
                $('#'+form_name+' button').button('disable');
                $('#'+form_name+' .formMessage').removeClass('green red bold').addClass('loading').html('<i>'+__('Saving..')+'</i>');
            },
            complete: function () {
                $('#'+form_name).removeAttr('disabled');
                $('#'+form_name+' button').button('enable');
                $('#'+form_name+' .formMessage').removeClass('loading');
            },
            success: function (json) {
                if (json.status) {
                    $('#'+grid_name).flexReload();
                    $('#'+form_name+' .formMessage').addClass('green bold').html(json.mesg);
                    setTimeout(function(){
                        $('#'+dialog2).dialog('close');
                        $('#'+form_name+' .formMessage').html('');
                    }, 1000);
                } else {
                    if ($.isArray(json.error)) {
                        jQuery.each(json.error, function() {
                            $.validationEngine.buildPrompt('#'+ext+this.f, this.m, 'error');
                        });
                    }

                    var msg = (json.mesg) ? json.mesg : '';
                    $('#'+form_name+' .formMessage').addClass('red bold').html(msg);
                }
            },
            error: function () {
                message('Error found while in saving..', 'error');
            }
        });

        return false;
    }, // save

    edit: function(id) {
        var data = selectRecord(this.dialog1, id);
        var ext  = this.ext;

        populate(ext, data, ['rate_code_id', 'room_type_id']);

        jQuery.each(data.fields, function(i, field){
            if ($('#'+ext+field).length && field == 'room_type_id') {
                var value = data.values.slice(i, i+1);
                $('#'+ext+'room_type_id').linkselect('val', value);
            }
        });

        this.form('edit');
    } // edit
};

var hotel = {
    ext: 'htl-',
    dialog1: 'hotel-info-wrap',
    dialog2: 'hotel-form-wrap',
    form_name: 'HotelSaveForm',
    grid_name: 'hotellist',
    opener: false,

    open: function() {
        if (!$('.ui-dialog #'+this.dialog1).length) {
            hotel.grid();

            var grid_name = this.grid_name;
            $('#'+this.dialog1).dialog({
                width: 'auto',
                resizable: false,
                close: function(evet, ui){
                    setTimeout(function(){
                        $('#'+grid_name+' tr[class*=\'trSelected\']').removeClass('trSelected');
                    }, 800);
                }
            });

            return;
        }

        $('#'+this.dialog1).dialog('open');
    }, // open

    grid: function() {
        $('#'+this.grid_name).flexigrid({
            url: _webroot+'/hotels/listing',
            dataType: 'json',
            colModel: [
                { display: 'ID', name: 'id', width: 40, sortable: true, align: 'right' },
                { display: 'Hotel Name', name: 'name', width: 80, sortable: true, align: 'left' },
                { display: 'Street', name: 'street', width: 80, sortable: true, align: 'left' },
                { display: 'City', name: 'city', width: 60, sortable: true, align: 'left' },
                { display: 'State', name: 'state', width: 60, sortable: true, align: 'left' },
                { display: 'Zip Code', name: 'zip_code', width: 60, sortable: true, align: 'left' },
                { display: 'Phone', name: 'phone', width: 60, sortable: true, align: 'left' },
                { display: 'Fax', name: 'fax', width: 60, sortable: true, align: 'left' },
                { display: 'Email', name: 'email', width: 80, sortable: true, align: 'left' },
                { display: 'Creation', name: 'created', width: 100, sortable: true, align: 'center', hide: true },
                { display: 'Date Modified', name: 'modified', width: 100, sortable: true, align: 'center', hide: true },
                { display: 'Act', name: 'actions', width: 52, align: 'center' }
            ],
            buttons: [
                { name: 'Add', bclass: 'add', onpress: function(name){ hotel.form(name); } },
                { separator: true },
                { name: 'Delete', bclass: 'delete', onpress: function(name){ hotel.update(name); } },
                { separator: true }
            ],
            searchitems: [
                { display: 'ID', name: 'id' },
                { display: 'Hotel Name', name: 'name' },
                { display: 'City', name: 'city' },
                { display: 'Phone', name: 'phone' },
                { display: 'Email', name: 'email' }
            ],
            sortname: 'id',
            sortorder: 'asc',
            usepager: true,
            useRp: true,
            rp: 15,
            resizable: true,
            showTableToggleBtn: true,
            width: 780,
            height: 300
        });
    }, // grid

    form: function(act) {
        if (!$('.ui-dialog #'+this.dialog2).length) {
            var ext       = this.ext;
            var form_name = this.form_name;
            var grid_name = this.grid_name;

            $('#'+this.dialog2).dialog({
                width: 'auto',
                resizable: false,
                modal: true,
                open: function(event, ui) {
                    $('#'+ext+'name').focus();
                },
                close: function(event, ui) {
                    $.validationEngine.closePrompt('.formError');
                    $('#'+form_name+' .formMessage').html('');
                    $('#'+grid_name+' tr[class*=\'trSelected\']').removeClass('trSelected');
                },
                dragStart: function(event, ui) {
                    $.validationEngine.closePrompt('.formError');
                }
            });

            $('#'+form_name).validationEngine();
        }

        if (act != 'edit') { // create new record
            clearForm(this.form_name);
        }

        $('#'+this.dialog2).dialog('open');
    }, // form

    save: function() {
        var ext       = this.ext;
        var dialog2   = this.dialog2;
        var form_name = this.form_name;
        var grid_name = this.grid_name;

        if (!$('#'+form_name).validationEngine({ returnIsValid:true })) {
            return false;
        }

        $.ajax({
            type: 'POST',
            url: $('#'+form_name).attr('action'),
            data: $('#'+form_name).serialize(),
            dataType: 'json',
            beforeSend: function () {
                $('#'+form_name).attr('disabled', 'disabled');
                $('#'+form_name+' button').button('disable');
                $('#'+form_name+' .formMessage').removeClass('green red bold').addClass('loading').html('<i>'+__('Saving..')+'</i>');
            },
            complete: function () {
                $('#'+form_name).removeAttr('disabled');
                $('#'+form_name+' button').button('enable');
                $('#'+form_name+' .formMessage').removeClass('loading');
            },
            success: function (json) {
                if (json.status) {
                    $('#'+grid_name).flexReload();
                    $('#'+form_name+' .formMessage').addClass('green bold').html(json.mesg);
                    setTimeout(function(){
                        $('#'+dialog2).dialog('close');
                        $('#'+form_name+' .formMessage').html('');
                    }, 1000);
                } else {
                    if ($.isArray(json.error)) {
                        jQuery.each(json.error, function() {
                            $.validationEngine.buildPrompt('#'+ext+this.f, this.m, 'error');
                        });
                    }

                    var msg = (json.mesg) ? json.mesg : '';
                    $('#'+form_name+' .formMessage').addClass('red bold').html(msg);
                }
            },
            error: function () {
                $('#'+form_name+' .formMessage').html('');
                message(__('Error found while in saving..'), 'error');
            }
        });

        return false;
    }, //save

    edit: function(id) {
        var data = selectRecord(this.dialog1, id);

        if (!$.isArray(data.fields) || !$.isArray(data.values)) {
            return;
        }

        populate(this.ext, data);
        this.form('edit');
    }, // edit

    select: function(id) {

    }, // select

    update: function(act) {
        var ids = selectedRows(this.grid_name);
        var act = act.toLowerCase();
        var msg = '';

        if (ids.length == 0) {
            message(str_replace('{action}', act, __('Please select the row that want to {action}.')));
            return;
        } else if (ids.length > 1) {
            msg = str_replace(['{action}', '{no}'], [act, ids.length], __('Are you sure you want to {action} these {no} selected records?'));
            ids = ids.join(',');
        } else if (ids.length == 1) {
            msg = str_replace('{action}', act, __('Are you sure you want to {action} this selected record?'));
            ids = ids[0];
        }

        if (!confirm(msg)) {
            return;
        }

        var grid_name = this.grid_name;
        var dialog1   = this.dialog1;
        var statusTxt = '';

        $.ajax({
            type: 'POST',
            url: _webroot+'/hotels/update/',
            data: 'id='+ids+'&task='+act,
            dataType: 'json',
            beforeSend: function() {
                statusTxt = $('#'+dialog1+' span.pPageStat').html();

                $('#'+dialog1+' span.pPageStat').text(__('Processing, please wait ...'));
                $('#'+dialog1+' div.pReload').addClass('loading');
            },
            success: function(json) {
                if (json.status) {
                    $('#'+grid_name).flexReload();
                } else if (json.mesg) {
                    $('#'+dialog1+' span.pPageStat').html(statusTxt);
                    $('#'+dialog1+' div.pReload').removeClass('loading');
                    message(json.mesg, 'error');
                }
            },
            error: function() {
                message(__('Error found while in updating'), 'error');
            }
        });
    }
};



function loadContent (id, options) {
    var settings = {
        type: 'POST',
        beforeSend: function () {
            $('#'+id).html('<i>loading..</i>');
        },
        success: function (html) {
            $('#'+id).html(html);
        },
        error: function () {
            $('#'+id).html('<span class="red italic">error..</span>');
        }
    };
    jQuery.extend(settings, options);

    $.ajax(settings);
} // loadContent

function changeDate (ext, opr, staticFld, changeFld1, changeFld2) {
    var staticDate = $('#'+ext+staticFld).val();
    var nights     = parseInt($('#'+ext+'nights').val());
    var aryDate    = split('-', staticDate);

    var staticTime   = strtotime(aryDate[2]+'-'+aryDate[1]+'-'+aryDate[0]);
    var changingTime = strtotime(opr+nights+' day', staticTime);
    var changingDate = date('d-m-Y', changingTime);

    $('#'+ext+changeFld1).val(changingDate);
    $('#'+ext+changeFld2).val(date('l', changingTime));
} // changeDate

function changeStayNights (ext) {
    var checkinDate  = $('#'+ext+'check-in_date').val();
    var checkoutDate = $('#'+ext+'check-out_date').val();
    var aryDate      = split('-', checkinDate);
    var checkinTime  = strtotime(aryDate[2]+'-'+aryDate[1]+'-'+aryDate[0]);
    var checkoutTime = 0;

    aryDate      = split('-', checkoutDate);
    checkoutTime = strtotime(aryDate[2]+'-'+aryDate[1]+'-'+aryDate[0]);
    nights       = (checkoutTime - checkinTime) / 86400;

    $('#'+ext+'nights').val(nights);
} // changeStayNights

function datetime (dateObj) {
    var curr_date  = dateObj.getDate();
    var curr_month = dateObj.getMonth() + 1;
    var curr_year  = dateObj.getFullYear();
    var curr_time  = dateObj.getTime();

    curr_date  = (curr_date < 10) ? '0'+curr_date : curr_date;
    curr_month = (curr_month < 10) ? '0'+curr_month : curr_month;

    return {
        date: curr_date,
        month: curr_month,
        year: curr_year,
        time: curr_time
    };
} // datetime

function getDate (format) {
    if (format == 'today') {
        var d = new Date();
        var o = datetime(d);
        return o.date+'-'+o.month+'-'+o.year;
    } else if (format == 'tomorrow') {
        var d = new Date();
        var t = d.getTime() + 86400000;

        d = new Date(t);

        var o = datetime(d);
        return o.date+'-'+o.month+'-'+o.year;
    } else if (format == 'day') {
        var d = new Date();
        return _weekdays[d.getDay()];
    } else if (format == 'tomorrow day') {
        var d = new Date();
        var t = d.getTime() + 86400000;

        d = new Date(t);
        return _weekdays[d.getDay()];
    }
} // getDate

function next (id, page) {
    var width = $('#'+id).width();

    if ($.browser.opera) {
        page++;
        $('#'+id+' > div.inner-panel > .pages').css('display', 'none');
        $('#'+id+page).css({ 'position':'absolute', 'left':width }).show();
        $('#'+id+page).animate({ left:'0' }, { easing:'swing', complete:function(){ $(this).css('position', 'static'); } });
    } else {
        $('#'+id).stop().scrollTo({ top:0, left:'+='+width }, 500, { easing:'swing' });
    }
} // next

function prev (id, page) {
    var width = $('#'+id).width();

    if ($.browser.opera) {
        page--;
        width = width - (width*2);
        $('#'+id+' > div.inner-panel > .pages').css('display', 'none');
        $('#'+id+page).css({ 'position':'absolute', 'left':width }).show();
        $('#'+id+page).animate({ left:'0' }, { easing:'swing', complete:function(){ $(this).css('position', 'static'); } });
    } else {
        $('#'+id).stop().scrollTo({ top:0, left:'-='+width }, 500, { easing:'swing' });
    }
} // prev

function selectedRows (grid_name) {
    var ids  = new Array();
    var rows = $('#'+grid_name+' tr.trSelected > td:first-child > div');

    jQuery.each(rows, function(){
        ids.push($(this).text());
    });

    return ids;
} // selectedRows

function selectRecord (dialog, grid_id) {
    var data   = new Array();
    var fields = new Array();

    jQuery.each($('#'+dialog+' div.flexigrid div.hDiv div.hDivBox table tr th[abbr]'), function(){
        fields.push($(this).attr('abbr'));
    });

    jQuery.each($('#'+dialog+' div.flexigrid div.bDiv table tr[id^=\'row\']'), function(){
        var id = $(this).attr('id').replace('row', '');
        if (id == grid_id) {
            jQuery.each($('#'+dialog+' div.flexigrid div.bDiv table tr#row'+id+' td div'), function(){
                var value = $(this).text().replace(/^\s*/, '');
                data.push(value);
            });
        }
    });

    /*var obj = jQuery.map(fields, function(n, i){
                  return n+":'"+data.slice(i, i+1)+"'";
    });*/

    return { fields:fields, values:data };
} // selectRecord

function populate (prefix, data, loadingFields) {
    jQuery.each(data.fields, function(i, field){
        if ($('#'+prefix+field).length) {
            $('#'+prefix+field).val(data.values.slice(i, i+1));
        } else if ($.isArray(loadingFields) && jQuery.inArray(field, loadingFields) != -1) { // form object may in loading..
            populateRetry(0, prefix+field, data.values.slice(i, i+1));
        }
    });
} // populate

function populateRetry (retry, field, value) {
    retry++;

    if (retry > 20) { // 20 second timeout
        return;
    }

    if ($('#'+field).length) { // found it now
        cInfo('Found '+field+' and populate value ['+value+'] now!');
        $('#'+field).val(value);
    } else {
        setTimeout(function(){
            clog('Retry '+field+' no#'+retry);
            populateRetry(retry, field, value);
        }, 1000);
    }
} // populateRetry

function clearForm (form) {
    $('#'+form+' input[type=\'text\'], #'+form+' input[type=\'hidden\'], #'+form+' textarea, #'+form+'input[class!=\'default\']').val('');
    jQuery.each($('#'+form+' select option:first-child'), function(){
        $(this).attr('selected', 'selected');
    });
} // clearForm

function message (mesg, icon, options) {
    if (typeof(icon) != 'undefined') {
        $('#message-icon').attr('class', icon);
    } else {
        $('#message-icon').attr('class', 'warning');
    }

    $('#message-body').html(mesg);
    $('#dialog-message').dialog('open');
} // message

function __ (msgstr) {
    clog('translate msgstr: '+msgstr);
    return msgstr;
} // __

function clog (msg) {
    //console.log(msg);
} // clog

function cInfo (msg) {
    //console.info(msg);
} // cInfo